package com.example.romibotest;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

//import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
//import android.os.Bundle;
import android.util.Log;

/***
 * This is the simplest bluetooth program. It sends one message to one bluetooth
 * device. The message and the bluetooth hardware id for the device are hard
 * coded. <br>
 * <br>
 * It does <b>not</b> receive any data. It does not do any thread processing. <br>
 * <br>
 * 
 * This application will be useful to communicate with a bluetooth hardware
 * device such as a bar code reader, Lego Mindstorm, a PC with a com port
 * application, a PC with a terminal program with 'listening' to a com port, a
 * second android device with a terminal program such as <a href=
 * "http://www.tec-it.com/en/software/data-acquisition/getblue/android-smartphone/Default.aspx"
 * >GetBlue</a>. It is not a full android bluetooth application but more a proof
 * of concept that the bluetooth works.
 * 
 * <br>
 * <br>
 * 
 * This code should cut and paste into the <a
 * href="http://developer.android.com/resources/tutorials/hello-world.html>
 * 'HelloAndroid' example</a>. It does not use any screen io.
 * 
 * Add to your Android Manifest.xml file: <uses-permission
 * android:name="android.permission.BLUETOOTH" /> <uses-permission
 * android:name="android.permission.BLUETOOTH_ADMIN" />
 * 
 * For a proper bluetooth example with threading and receiving data see: <a
 * href=
 * "http://developer.android.com/resources/samples/BluetoothChat/index.html"
 * >http://developer.android.com/resources/samples/BluetoothChat/index.html</a>
 * 
 * @see <a
 *      href="http://developer.android.com/guide/topics/wireless/bluetooth.html">
 *      http://developer.android.com/guide/topics/wireless/bluetooth.html</a>
 * 
 */
public class Bluetooth{

	/** The BluetoothAdapter is the gateway to all bluetooth functions **/
	protected BluetoothAdapter bluetoothAdapter = null;

	/** We will write our message to the socket **/
	protected BluetoothSocket socket = null;

	/** The Bluetooth is an external device, which will receive our message **/
	BluetoothDevice blueToothDevice = null;

	/** Called when the activity is first created. 
	 * @return */
	public Bluetooth() {
		//setContentView(R.layout.activity_main);

		// Grab the BlueToothAdapter. The first line of most bluetooth programs.
		bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

		// if the BluetoothAdapter.getDefaultAdapter(); returns null then the
		// device does not have bluetooth hardware. Currently the emulator
		// does not support bluetooth so this will this condition will be true.
		// i.e. This code only runs on a hardware device an not on the emulator.
		if (bluetoothAdapter == null) {
			Log.e(this.toString(), "Bluetooth Not Available.");
			return;
		}

		// This will find the remote device given the bluetooth hardware
		// address.
		// @todo: Change the address to the your device address
		//blueToothDevice = bluetoothAdapter.getRemoteDevice("00:02:72:AA:C4:C8"); //darwin
		blueToothDevice = bluetoothAdapter.getRemoteDevice("20:13:02:19:14:27");  //romibo
		/*for (Integer port = 1; port <= 3; port++) {
			simpleComm(Integer.valueOf(port));
		}*/
	}
	
	public void connect(){
		// The documents tell us to cancel the discovery process.
				bluetoothAdapter.cancelDiscovery();

				//Log.d(this.toString(), "Port = " + port);
				try {
					Integer port = 1;
					// This is a hack to access "createRfcommSocket which is does not
					// have public access in the current api.
					// Note: BlueToothDevice.createRfcommSocketToServiceRecord (UUID
					// uuid) does not work in this type of application. .
					Method m = blueToothDevice.getClass().getMethod(
							"createRfcommSocket", new Class[] { int.class });
					socket = (BluetoothSocket) m.invoke(blueToothDevice, port);

					// debug check to ensure socket was set.
					assert (socket != null) : "Socket is Null";

					// attempt to connect to device
					socket.connect();
					try {
						Log.d(this.toString(),
								"************ CONNECTION SUCCEES! *************");

						// Grab the outputStream. This stream will send bytes to the
						// external/second device. i.e it will sent it out.
						// Note: this is a Java.io.OutputStream which is used in several
						// types of Java programs such as file io, so you may be
						// familiar with it.
						//OutputStream outputStream = socket.getOutputStream();

						// Create the String to send to the second device.
						// Most devices require a '\r' or '\n' or both at the end of the
						// string.
						// @todo set your message
						//String message = "Data from Android and tester program!\r";

						// Convert the message to bytes and blast it through the
						// bluetooth
					// to the second device. You may want to use:
					// public byte[] getBytes (Charset charset) for proper String to
					// byte conversion.
					//outputStream.write(callNumber.getBytes());

				} finally {
					// close the socket and we are done.
					//socket.close();
				}
				// IOExcecption is thrown if connect fails.
			} catch (IOException ex) {
				Log.e(this.toString(), "IOException " + ex.getMessage());
				// NoSuchMethodException IllegalAccessException
				// InvocationTargetException
				// are reflection exceptions.
			} catch (NoSuchMethodException ex) {
				Log.e(this.toString(), "NoSuchMethodException " + ex.getMessage());
			} catch (IllegalAccessException ex) {
				Log.e(this.toString(), "IllegalAccessException " + ex.getMessage());
			} catch (InvocationTargetException ex) {
				Log.e(this.toString(),
						"InvocationTargetException " + ex.getMessage());
			}
	}
	
	public void callComm(String callNumber){
		//for (Integer port = 1; port <= 3; port++) {
		for (Integer port = 1; port <= 1; port++) {
			simpleComm(Integer.valueOf(port),callNumber);
		}
	}

	protected void simpleComm(Integer port, String callNumber) {
		// byte [] inputBytes = null;

		// The documents tell us to cancel the discovery process.
		//bluetoothAdapter.cancelDiscovery();

		//Log.d(this.toString(), "Port = " + port);
		//try {
			// This is a hack to access "createRfcommSocket which is does not
			// have public access in the current api.
			// Note: BlueToothDevice.createRfcommSocketToServiceRecord (UUID
			// uuid) does not work in this type of application. .
			//Method m = blueToothDevice.getClass().getMethod(
				//	"createRfcommSocket", new Class[] { int.class });
			//socket = (BluetoothSocket) m.invoke(blueToothDevice, port);

			// debug check to ensure socket was set.
			//assert (socket != null) : "Socket is Null";

			// attempt to connect to device
			//socket.connect();
			//try {
				//Log.d(this.toString(),
				//		"************ CONNECTION SUCCEES! *************");

				// Grab the outputStream. This stream will send bytes to the
				// external/second device. i.e it will sent it out.
				// Note: this is a Java.io.OutputStream which is used in several
				// types of Java programs such as file io, so you may be
				// familiar with it.
				OutputStream outputStream = null;
				try {
					outputStream = socket.getOutputStream();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}

				// Create the String to send to the second device.
				// Most devices require a '\r' or '\n' or both at the end of the
				// string.
				// @todo set your message
				//String message = "Data from Android and tester program!\r";

				// Convert the message to bytes and blast it through the
				// bluetooth
			// to the second device. You may want to use:
			// public byte[] getBytes (Charset charset) for proper String to
			// byte conversion.
			try {
				outputStream.write(callNumber.getBytes());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		//} finally {
			// close the socket and we are done.
			//socket.close();
		//}
		// IOExcecption is thrown if connect fails.
	//} catch (IOException ex) {
		//Log.e(this.toString(), "IOException " + ex.getMessage());
		// NoSuchMethodException IllegalAccessException
		// InvocationTargetException
		// are reflection exceptions.
	//} catch (NoSuchMethodException ex) {
	//	Log.e(this.toString(), "NoSuchMethodException " + ex.getMessage());
	//} catch (IllegalAccessException ex) {
	//	Log.e(this.toString(), "IllegalAccessException " + ex.getMessage());
	//} catch (InvocationTargetException ex) {
		//Log.e(this.toString(),
		//		"InvocationTargetException " + ex.getMessage());
	
}

}
